﻿using DotNet5.Mvc.Common;
using DotNet5.Mvc.FreeSqlBuilder;
using FreeSql;
using System;
using System.Diagnostics;
using System.Linq.Expressions;

namespace DotNet5.Mvc.Repositories.Impl
{
    public partial class BaseRepositories<T> where T : class, new()
    {
        protected readonly IFreeSql fsql = FreeSqlFactory.CreateFreeSql();

        public void Create(T t)
        {
            fsql.Insert<T>(t);
        }

        public void Update(T t)
        {
            fsql.Update<T>(t);
        }

        public void Delete(T t)
        {
            fsql.Delete<T>(t);
        }

        public void DeleteById(string[] id)
        {
            int delCount = fsql.Delete<T>(id).ExecuteAffrows();
            Trace.WriteLine($"共删除了【{ delCount }】条数据。");
        }

        public ISelect<T> GetModelsAll()
        {
            return fsql.Select<T>();
        }

        public ISelect<T> GetModels<type>(bool isAsc, Expression<Func<T, type>> orderByExpression, Expression<Func<T, bool>> whereExpression)
        {
            if (isAsc)
            {
                return fsql.Select<T>().OrderBy(orderByExpression).Where(whereExpression);
            }
            else
            {
                return fsql.Select<T>().OrderByDescending(orderByExpression).Where(whereExpression);
            }
        }

        public PageObject<T> GetModelsByPage<type>(int page, int limit, bool isAsc, Expression<Func<T, type>> orderByExpression, Expression<Func<T, bool>> whereExpression)
        {
            PageObject<T> po = new PageObject<T>();
            long total = 0;
            if (isAsc)
            {
                po.Rows = fsql.Select<T>().Where(whereExpression).OrderBy(orderByExpression).Count(out total).Page(page, limit).ToList();
            }
            else
            {
                po.Rows = fsql.Select<T>().Where(whereExpression).OrderByDescending(orderByExpression).Count(out total).Page(page, limit).ToList();
            }
            po.Total = total;
            return po;
        }

        public T GetModelsById(int id)
        {
            return fsql.Select<T>(id).First();
        }


    }
}
